package main

import (
	"github.com/codegangsta/negroni"
	"log"
	"net/http"
	"time"
)

//https://codegangsta.gitbooks.io/building-web-apps-with-go/content/middleware/index.html
func main() {
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(MyMiddleWare),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)
	n.Run(":8080")
}

func MyMiddleWare(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	now := time.Now().Nanosecond()
	log.Println("Logging on the way there...")
	if r.URL.Query().Get("password") == "secret123" {
		next(rw, r)
	} else {
		http.Error(rw, "Not Authorized", 401)
	}
	now = time.Now().Nanosecond() - now
	var ms = float64(now) / 10e6
	log.Println("Logging on the way back, cost:", ms, " ms")
}
